package com.mlc.core.serviceImpl;

import com.mlc.core.dto.RequestDto;
import com.mlc.data.entity.Users;
import com.mlc.data.dao.UsersDao;
import com.mlc.core.service.UsersService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author FireWang
 * @date 2022/03/14 02:43:39
 */
@Service
@AllArgsConstructor
@Transactional
public class UsersServiceImpl implements UsersService {
    private UsersDao usersDao;

    @Override
    public List<Users> getAll() {
        return usersDao.findAll();
    }

    @Override
    public Users getById(Integer id) {
        Optional<Users> users = usersDao.findById(id);
        return users.get();
    }

    @Override
    public Users insert(RequestDto loginDto) {
        Users user = Users.builder()
                .userType(1)
                .phone(loginDto.getPhone())
                .openId(loginDto.getOpenId())
                .nickName(loginDto.getNickName())
                .gender(loginDto.getGender())
                .country(loginDto.getCountry())
                .province(loginDto.getProvince())
                .city(loginDto.getCity())
                .avatarUrl(loginDto.getAvatarUrl())
                .language(loginDto.getLanguage())
                .loginTimes(0)
                .balance(0)
                .bonusPoints(0)
                .status(1)
                .createTime(new Date())
                .build();
        return usersDao.save(user);
    }

    @Override
    public void update(Users users) {
        users.setModifyTime(new Date());
        usersDao.save(users);
    }

    @Override
    public void deleteById(Integer id) {
        usersDao.deleteById(id);
    }

    @Override
    public Users exist(RequestDto loginDto) throws Exception {
        Optional<Users> users = usersDao.findById(loginDto.getUserId());
        if (users.isPresent()) {
            return users.get();
        }

        List<Users> users1 = usersDao.findByPhone(loginDto.getPhone());
        if (users1.size() > 0) {
            return users1.get(0);
        }

        List<Users> users2 = usersDao.findByOpenId(loginDto.getOpenId());
        if (users2.size() > 0) {
            return users2.get(0);
        }

        List<Users> users3 = usersDao.findByUserName(loginDto.getUserName());
        if (users3.size() > 0) {
            return users3.get(0);
        }

        return null;
    }

    @Override
    public void increaseBonusPoints(int userId, int bonusPoints) throws Exception {
        Optional<Users> users = usersDao.findById(userId);
        if (users.isPresent()) {
            Users user = users.get();
            user.setBonusPoints(user.getBonusPoints() + bonusPoints);
            usersDao.save(user);
        }
    }

}